//
//  BaseViewController.m
//  HuaiWu
//
//  Created by HuaiWu on 2022.
//  Copyright © 2022 HuaiWu. All rights reserved.
//

#import "BaseViewController.h"
#import "HWSubscribeViewController.h" //订阅页面
#import "BaseWebViewController.h"

#import "HWProgressHUD.h"

@interface BaseViewController ()

@property (nonatomic, strong) HWProgressHUD *progressHUD;

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kViewBackgroundColor;
    
    [self.view addSubview:self.navigationBar];
    _pageIndex = 1;
    [self showBack];
    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr
{
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
}

//成功刷新界面
- (void)subscriptionSuccessfullyRefreshed {

}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return kStatusBarStyle;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)pushViewControllerWithName:(id)classOrName {
    if (classOrName) {
        Class classs;
        if ([classOrName isKindOfClass:[NSString class]]) {
            NSString *name = classOrName;
            classs = NSClassFromString(name);
        } else if ([classOrName isSubclassOfClass:[BaseViewController class]]) {
            classs = classOrName;
        }
        
        UIViewController *vc = [classs new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)returnViewControllerWithName:(id)classOrName {
    if (classOrName) {
        Class classs;
        if ([classOrName isKindOfClass:[NSString class]]) {
            NSString *name = classOrName;
            classs = NSClassFromString(name);
        } else if ([classOrName isSubclassOfClass:[BaseViewController class]]) {
            classs = classOrName;
        }
        
        [self.navigationController.viewControllers enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:classs]) {
                [self.navigationController popToViewController:obj animated:YES];
                *stop = YES;
                return;
            }
        }];
    }
}

#pragma mark 导航定制

- (void)setNavigationItemTitleViewWithBlackTitle:(NSString *)title {
    if (title.length == 0) {
        return;
    }
    
    if (!_titleView) {
        _titleView = [UIView new];
    }
    _titleView.backgroundColor = [UIColor clearColor];
    
    // 移除之前的子控件
    [_titleView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateHighlighted];
    [btn setTitleColor:UIColorFromHex(0x000000) forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromHex(0x000000) forState:UIControlStateHighlighted];
    CGSize titleSize = [title ex_sizeWithFont:btn.titleLabel.font constrainedToSize:CGSizeMake(kScreenWidth, MAXFLOAT)];
    float leight = MIN(kScreenWidth - 90.f, titleSize.width);
    _titleView.frame = CGRectMake(kScreenWidth/2 - leight/2, self.statusBarHeight, leight, self.navigationBar.frame.size.height - self.statusBarHeight);
    btn.frame = CGRectMake(0, 0, _titleView.frame.size.width, _titleView.frame.size.height);
    [_titleView addSubview:btn];
    [self.navigationBar addSubview:_titleView];
}

- (void)setNavigationItemTitleViewWithTitle:(NSString *)title {
    if (title.length == 0) {
        return;
    }
    
    if (!_titleView) {
        _titleView = [UIView new];
    }
    _titleView.backgroundColor = [UIColor clearColor];
    
    // 移除之前的子控件
    [_titleView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateHighlighted];
    [btn setTitleColor:kUIToneTextColor forState:UIControlStateNormal];
    [btn setTitleColor:kUIToneTextColor forState:UIControlStateHighlighted];
    CGSize titleSize = [title ex_sizeWithFont:btn.titleLabel.font constrainedToSize:CGSizeMake(kScreenWidth, MAXFLOAT)];
    float leight = MIN(kScreenWidth - 90.f, titleSize.width);
    _titleView.frame = CGRectMake(kScreenWidth/2 - leight/2, self.statusBarHeight, leight, self.navigationBar.frame.size.height - self.statusBarHeight);
    btn.frame = CGRectMake(0, 0, _titleView.frame.size.width, _titleView.frame.size.height);
    [_titleView addSubview:btn];
    [self.navigationBar addSubview:_titleView];
}

- (void)showBack {
    NSString *imageName = @"black_back";
    [self setLeftItemWithIcon:[UIImage imageNamed:imageName] selector:@selector(backAction:)];
}

- (void)backAction:(UIButton *)sender {
    [SVProgressHUD dismiss];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setLeftItemWithIcon:(UIImage *)icon selector:(SEL)selector {
    [self.navigationBar addSubview:[self ittemLeftItemWithIcon:icon selector:selector]];
}

- (void)setLeftItemWithTitle:(NSString *)title selector:(SEL)selector {
    [self.navigationBar addSubview:[self ittemLeftItemWithTitle:title selector:selector]];
}

- (UIView *)ittemLeftItemWithTitle:(NSString *)title selector:(SEL)selector {
    UIView *item;
    if (title.length == 0) {
        item = [UIView new];
        return item;
    }
    
    if (!_leftItem) {
        _leftItem = [UIView new];
    }
    _leftItem.backgroundColor = [UIColor clearColor];
    
    // 移除之前的子控件
    [_leftItem.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:18];

    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    if (selector) {
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    }
    [btn setTitle:[NSString stringWithFormat:@"%@",title] forState:UIControlStateNormal];
    [btn setTitle:[NSString stringWithFormat:@"%@",title] forState:UIControlStateHighlighted];
    [btn setTitleColor:UIColorFromHex(0x000000) forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromHex(0x000000) forState:UIControlStateHighlighted];
    CGSize titleSize = [[NSString stringWithFormat:@"%@",title] ex_sizeWithFont:btn.titleLabel.font constrainedToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT)];
    float leight = titleSize.width + 15*2;

    _leftItem.frame = CGRectMake(0, self.statusBarHeight, leight, self.navigationBar.frame.size.height - self.statusBarHeight);
    btn.frame = CGRectMake(0, 0, _leftItem.frame.size.width, _leftItem.frame.size.height);
    [_leftItem addSubview:btn];
    return _leftItem;
}

- (UIView *)ittemLeftItemWithIcon:(UIImage *)icon selector:(SEL)selector {
    UIView *item;
    if (!icon) {
        item = [UIView new];
        return item;
    }
    
    if (!_leftItem) {
        _leftItem = [UIView new];
    }
    _leftItem.backgroundColor = [UIColor clearColor];
    
    // 移除之前的子控件
    [_leftItem.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    if (selector) {
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    }
    float leight = 0;
    if (icon) {
        leight += (icon.size.width + 15*2);
        [btn setImage:icon forState:UIControlStateNormal];
        [btn setImage:icon forState:UIControlStateHighlighted];
    }

    _leftItem.frame = CGRectMake(0, self.statusBarHeight, leight, self.navigationBar.frame.size.height - self.statusBarHeight);
    btn.frame = CGRectMake(0, 0, _leftItem.frame.size.width, _leftItem.frame.size.height);
    [_leftItem addSubview:btn];
    return _leftItem;
}

- (void)setRightItemWithTitle:(NSString *)title selector:(SEL)selector {
    UIView *view = [self ittemRightItemWithTitle:title selector:selector];
    [self.navigationBar addSubview:view];
}

- (void)setRightItemWithIcon:(UIImage *)icon selector:(SEL)selector {
    UIView *view = [self ittemRightItemWithIcon:icon selector:selector];
    [self.navigationBar addSubview:view];
}

- (UIView *)ittemRightItemWithIcon:(UIImage *)icon selector:(SEL)selector {
    UIView *item;
    if (!icon) {
        item = [UIView new];
        return item;
    }
    
    if (!_rightItem) {
        _rightItem = [UIView new];
    }
    _rightItem.backgroundColor = [UIColor clearColor];
    
    // 移除之前的子控件
    [_rightItem.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    if (selector) {
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    }
    float leight = icon.size.width + 15*2;
    [btn setImage:icon forState:UIControlStateNormal];
    [btn setImage:icon forState:UIControlStateHighlighted];
    
    _rightItem.frame = CGRectMake(kScreenWidth - leight, self.statusBarHeight, leight, self.navigationBar.frame.size.height - self.statusBarHeight);
    btn.frame = CGRectMake(0, 0, _rightItem.frame.size.width, _rightItem.frame.size.height);
        
    [_rightItem addSubview:btn];
    return _rightItem;
}

- (UIView *)ittemRightItemWithTitle:(NSString *)title selector:(SEL)selector {
    UIView *item;
    if (title.length == 0) {
        item = [UIView new];
        return item;
    }
    
    if (!_rightItem) {
        _rightItem = [UIView new];
    }
    _rightItem.backgroundColor = [UIColor clearColor];
    
    // 移除之前的子控件
    [_rightItem.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    if (selector) {
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    }
    [btn setTitle:[NSString stringWithFormat:@"%@",title] forState:UIControlStateNormal];
    [btn setTitle:[NSString stringWithFormat:@"%@",title] forState:UIControlStateHighlighted];
    [btn setTitleColor:UIColorFromHex(0x3562EC) forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromHex(0x3562EC) forState:UIControlStateHighlighted];
    CGSize titleSize = [[NSString stringWithFormat:@"%@",title] ex_sizeWithFont:btn.titleLabel.font constrainedToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT)];
    float leight = titleSize.width + 15*2;

    _rightItem.frame = CGRectMake(kScreenWidth - leight, self.statusBarHeight, leight, self.navigationBar.frame.size.height - self.statusBarHeight);
    btn.frame = CGRectMake(0, 0, _rightItem.frame.size.width, _rightItem.frame.size.height);
    [_rightItem addSubview:btn];
    return _rightItem;
}

#pragma mark - Action

//显示提示界面
- (void)showProgressHUD:(NSString *)title {
    
    self.progressHUD.hidden = NO;
    
    [self.progressHUD setData:[HWProgressHUDModel ittemModelWithTitle:title] delegate:self];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.progressHUD.myView.alpha = 1.0;
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - goto

//订阅页
- (void)gotoSubscribeViewController {
    HWSubscribeViewController *vc = [HWSubscribeViewController new];
    vc.type = 1;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

//h5
- (void)gotoBaseWebViewController:(NSString *)title url:(NSString *)url {
    BaseWebViewController *vc = [BaseWebViewController new];
    if (url.length > 0) {
        vc.url = url;
    } else {
        if ([title isEqualToString:@"服务条款"]) {
            vc.url = kServiceUrl;
 
            
        } else if ([title isEqualToString:@"隐私政策"]) {
            vc.url = kPrivacyUrl;

        }
    }
    vc.webTitle = title;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - 高度
    
- (float)navigationBarHeight {
    return self.statusBarHeight + 50;
}

- (float)bottomBarHeight {
    if (@available(iOS 13.0, *)) {
        NSSet *set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *windowScene = [set anyObject];
        UIWindow *window = windowScene.windows.firstObject;
        return window.safeAreaInsets.bottom;
    } else if (@available(iOS 11.0, *)) {
        UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
        return window.safeAreaInsets.bottom;
    }
    if (self.isIphoneX) {
        return 33;
    }
    return 0;
}

//状态栏高度
- (float)statusBarHeight {
    if (@available(iOS 13.0, *)) {
        NSSet *set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *windowScene = [set anyObject];
        UIWindow *window = windowScene.windows.firstObject;
        return window.safeAreaInsets.top;
    } else if (@available(iOS 11.0, *)) {
        UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
        return window.safeAreaInsets.top;
    }
    if (self.isIphoneX) {
        return 44;
    }
    return 20;
}

#pragma mark - 设备判断
    
- (BOOL)isIphoneX {
    // 先判断当前设备是否为 iPhone 或 iPod touch
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        // 获取屏幕的宽度和高度，取较大一方判断是否为 812.0 或 896.0
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
        CGFloat maxLength = screenWidth > screenHeight ? screenWidth : screenHeight;
        if (maxLength == 812.0f || maxLength == 844.0f || maxLength == 896.0f || maxLength == 926.0f || maxLength == 932.0f) {
            return YES;
        }
    }
    return NO;
}

#pragma mark - 懒加载

- (UIView *)navigationBar {
    if (!_navigationBar) {
        _navigationBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, self.navigationBarHeight)];
        _navigationBar.backgroundColor = kUIToneBackgroundColor;
    }
    return _navigationBar;
}

- (HWProgressHUD *)progressHUD {
    if (!_progressHUD) {
        _progressHUD  = [HWProgressHUD instanceView];
        _progressHUD.frame = CGRectMake(0,0, kScreenWidth, kScreenHeight);
        _progressHUD.myView.alpha = 0;
        [self.view addSubview:_progressHUD];
    }
    return _progressHUD;
}

@end
